import 'package:cloudapp/esdk/esync.dart';
import 'package:cloudapp/esdk/response/file_list_item.dart';
import 'package:cloudapp/items/picture_file_item.dart';
import 'package:cloudapp/pages/album_viewer.dart';
import 'package:cloudapp/pages/base.dart';
import 'package:cloudapp/pages/video_player_page.dart';
import 'package:flutter/material.dart';


class PictureListPage extends StatefulWidget {
  final int albumId;
  static const pageName = "/picture/list";
  PictureListPage({Key key, @required this.albumId}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PictureListPage();
  }
}

class _PictureListPage extends BaseState<PictureListPage> {
  final List<FileListItem> _files = [];

  @override
  void initState() {
    super.initState();
    print('AlbumID: ${widget.albumId}');
    Future.delayed(Duration.zero, loadFiles);
  }

  Future<void> loadFiles() async {
    withExc(() async {
      var rs = await ESync.i().getAlbumFileList(widget.albumId);

      setState(() {
        _files.clear();
        for(var item in rs) {
          _files.add(item);
        }
      });
    });
  }

  void openPictureViewer(int index) {
    var args = AlbumViewerArguments(
      albums: _files,
      index: index,
    );
    Navigator.pushNamed(context, AlbumViewerPage.pageName, arguments: args);
  }

  void openVideoPlayer(int i) {
    var f = _files[i];
    var url = ESync.i().getFileRawUrl(f.id);
    Navigator.pushNamed(context, VideoPlayerPage.pageName, arguments: url);
  }

  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    for(var i=0; i!=_files.length; i++) {
      children.add(PictureFileItem(
        file: _files[i],
        onClick: () {
          var cur = _files[i];
          if(cur.cType.startsWith('video')) {
            openVideoPlayer(i);
          } else {
            openPictureViewer(i);
          }
        },
      ));
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('相册图片'),
      ),
      body: GridView.count(
        crossAxisCount: 4,
        childAspectRatio: 0.785,
        mainAxisSpacing: 1.0,
        crossAxisSpacing: 1.0,
        children: children,
      ),
    );
  }
}
